<?php

namespace app\manystore\controller;

use app\common\controller\ManystoreBase;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Lights extends ManystoreBase
{

    /**
     * Lights模型对象
     * @var \app\manystore\model\Lights
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Lights;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    $code_img=$this->getWxcode( $this->model->id,SHOP_ID);
                    $this->model->where('id','=', $this->model->id)->update(['code_img'=>$code_img]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code_number=\app\manystore\model\Lights::orderRaw('CAST(code AS UNSIGNED) DESC')->where('shop_id',SHOP_ID)->value('code');

        if ($code_number) {
            $newRoomNumber = intval($code_number) + 1; // 转换为整数后加1
        } else {
            $newRoomNumber = 1; // 从1开始
        }
        $this->view->assign("code", $newRoomNumber);
        return $this->view->fetch();
    }


    public function getWxAccessToken() {

        $appid = get_addon_config("loginmobile")['appId'];
        $secret = get_addon_config("loginmobile")['secretId'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = makeRequest($url);
        $access_token = json_decode($access_token['result'], true);

        return $access_token;
    }
    //获取二维码
    public function getWxcode($code,$shopid)
    {
        $ACCESS_TOKEN = $this->getWxAccessToken();
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN['access_token'];
        $post_data =
            array(
                'page' => 'pages/board/index',
                'scene' => $code.'_'.$shopid,
               // 'check_path' => false,
                'env_version' => 'release'
            );
        $post_data = json_encode($post_data);
        // 发送 POST 请求获取二维码数据
        $data = send_post($url, $post_data);

        // 检查返回结果是否有效
        if (isset($data['errcode']) && $data['errcode'] !== 0) {
            // 返回错误信息
            return json_encode(['error' => true, 'message' => $data['errmsg']]);
        }

        // 定义保存的目录和文件名
        $uploadDir = 'uploads/wx_codes/'; // 这里可以根据需要修改目录
        if (!is_dir($uploadDir)) {
            // 如果目录不存在，则创建它
            mkdir($uploadDir, 0755, true);
        }
        $fileName = uniqid('wx_code_') . '.png'; // 生成唯一的文件名
        $filePath = $uploadDir . $fileName;

        // 将二进制数据保存到文件
        file_put_contents($filePath, $data);

        // 获取文件的完整 URL
        $fullBaseUrl = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/';
        // 注意：确保此路径与您的应用相匹配
        $fileUrl = $fullBaseUrl . $filePath;

        return $fileUrl;

    }

}
